<template>
  <div class="chat-container">
    <!-- 消息列表 -->
    <div class="message-list">
      <div
          v-for="(message, index) in messages"
          :key="index"
          :class="['message', message.sender]"
      >
        <div class="message-content">
          {{ message }}
        </div>
        <div class="message-time">
          {{ message.time }}
        </div>
      </div>
    </div>

    <!-- 消息输入框 -->
    <div class="message-input">
      <el-input
          v-model="newMessage.content"
          placeholder="请输入消息"
          @keyup.enter="sendMessage"
      />
      <el-button type="primary" @click="sendMessage">发送</el-button>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import {chatSelectMessageList, chatSendMessage} from "@/api/chat.js";
import {ElMessage} from "element-plus";

// 消息列表
const messages = ref([]);

// 新消息
const newMessage = ref({});

// 接收props
const props = defineProps({
  chatData: {
    type: Object,
    required: true,
  },
});

// 发送消息
const sendMessage = async () => {
  newMessage.value.content = newMessage.value.content.trim();
  if (newMessage.value.content === '') {
    return;
  }
  newMessage.value.senderId = props.chatData.userId;
  newMessage.value.receiverId = props.chatData.doctorId;
  newMessage.value.messageType = 1;
  const res = await chatSendMessage(newMessage.value)
  if (res.code === 200) {
    ElMessage.success('发送成功');

  } else {
    ElMessage.error('发送失败');
  }
  newMessage.value = ''; // 清空输入框
  await historyMessages(); // 刷新消息列表
};

const historyMessages = async () => {
  const res = await chatSelectMessageList({senderId: props.chatData.userId, receiverId: props.chatData.doctorId})
  if (res.code === 200) {
    messages.value = res.data.reverse();
  }
}

onMounted(() => {
  historyMessages();
})
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 10px;
}

.message {
  display: flex;
  flex-direction: column;
  margin-bottom: 10px;
}

.message.me {
  align-items: flex-end;
}

.message.other {
  align-items: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f0f0f0;
}

.message.me .message-content {
  background-color: #409eff;
  color: white;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.message-input {
  display: flex;
  gap: 10px;
}
</style>
